package com.github.caijh.mall.validatecode.service.impl;

import javax.inject.Inject;

import com.github.caijh.commons.util.Images;
import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.framework.data.redis.Redis;
import com.github.caijh.mall.constants.Constants;
import com.github.caijh.mall.utils.ValidateCodeUtil;
import com.github.caijh.mall.validatecode.model.ValidateCode;
import com.github.caijh.mall.validatecode.service.ValidateCodeService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    public static String st = "fmZc8AgVI3jwYdL+RRLyL5e9Yl6SzD92";
    public static String sk = "0b7…）*#~Nel4MGKdoEaRagoxQ";
    @Inject
    private Redis redis;

    /**
     * 获取验证码信息
     */
    @Override
    public ValidateCode get() {
        ValidateCodeUtil.Validate randomCode = ValidateCodeUtil.getRandomCode();
        if (randomCode == null) {
            throw BizException.of("USER_VALID_CODE_GEN_ERROR");
        }

        String code = randomCode.getValue().toLowerCase();
        String md5Code = DigestUtils.md5Hex(code);
        String redisKey = key4ValidateCode(md5Code);
        redis.set(redisKey, code, Redis.Expired.M_1_SECONDS * 5);
        String base64Str = randomCode.getBase64Str();
        return new ValidateCode(md5Code, Images.INSTANCE.appendImageSchema(base64Str));
    }

    private String key4ValidateCode(String md5Key) {
        return Constants.VALIDATE_REDIS_KEY_PREFIX + md5Key;
    }

    /**
     * 验证
     *
     * @param validateCode ValidateCode
     */
    @Override
    public boolean check(ValidateCode validateCode) {
        String key = key4ValidateCode(validateCode.getKey());
        String code = redis.get(key);
        if (code == null) {
            throw BizException.of("USER_VALID_CODE_ERROR");
        }
        return code.equalsIgnoreCase(validateCode.getCode());
    }

}

